package com.ruoyi.common.file.obs;

import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.ruoyi.common.file.core.FileProperties;
import com.ruoyi.common.file.core.FileTemplate;
import lombok.RequiredArgsConstructor;

import java.io.InputStream;

/**
 * ClassName：ObsTemplate
 * Package：com.ruoyi.common.file.obs
 * Description：OBS具体实现操作类
 *
 * @Author：fpy
 * @Create：2025/5/7 - 10:07
 * @Version：v1.0
 */
@RequiredArgsConstructor
public class ObsTemplate implements FileTemplate {

    private final FileProperties fileProperties;

    private final ObsClient obsClient;

    @Override
    public void createBucket(String bucketName) {
        if (!obsClient.headBucket(bucketName)) {
            obsClient.createBucket(bucketName);
            setBucketPolicy(bucketName);
        }
    }

    @Override
    public Boolean bucketExists(String bucketName) {
        return obsClient.headBucket(bucketName);
    }

    @Override
    public void setBucketPolicy(String bucketName) {
        String policyJson = "{\"Statement\":[{"
                + "\"Principal\":\"*\","
                + "\"Effect\":\"Allow\","
                + "\"Action\":[\"GetObject\", \"DeleteObject\", \"PutObject\"],"
                + "\"Resource\":\"" + bucketName + "/*"
                + "\"}]}";

        obsClient.setBucketPolicy(bucketName, policyJson);
    }

    @Override
    public PutObjectResult putObject(String bucketName, String objectKey, InputStream input) {
        return obsClient.putObject(bucketName, objectKey, input);
    }

}
